const request = require('request');
const { env } = process;
/**
 * 发送模版消息
 * @param {*} openid 
 * @param {*} accessToken 
 * @param {*} taskInfo 
 * @param {*} userInfo 
 * @param {*} callFun 
 */
function _sendTmpMsg(openid,accessToken,taskInfo,userInfo,isCps,callFun){
    const url = `https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=${accessToken}`;
    const content = _strReplace(taskInfo.content,userInfo,taskInfo.wechatInfo,isCps);
    let _tmpUrl = taskInfo.url.replace(/\{domain\}/g,isCps?taskInfo.wechatInfo.tg_domain:taskInfo.wechatInfo.domain)
            .replace(/\{novel_domain}/g,taskInfo.wechatInfo.domain);
    
    const data =  {
        touser: openid,
        template_id: taskInfo.template_id,
        url: _tmpUrl,
        data: content
    };

    _sendPost(url,data,(err,res,body) => {
        callFun(err,body);
    });
}

/**
 * 发送文本消息
 * @param {*} openid 
 * @param {*} accessToken 
 * @param {*} taskInfo 
 * @param {*} userInfo 
 * @param {*} callFun 
 */
function _sendTextMsg(openid,accessToken,taskInfo,userInfo,isCps,callFun){
    const url = `https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=${accessToken}`
    let content = _strReplace(taskInfo.content,userInfo,taskInfo.wechatInfo,isCps,1);

    if(isCps){
        let _contentJson = JSON.parse(content);
        let _content = '';
        for(let v of _contentJson.articles){
            _content += `<a href="${v.url}">${v.title}</a>\n`;
        }
        content = _content;
    }
    const data = {
        touser: openid,
        msgtype: 'text',
        text:{content: content}
    }
    _sendPost(url,data,(err,res,body) => {
        callFun(err,body);
    });
}   

/**
 * 发送图文消息
 * @param {*} openid 
 * @param {*} accessToken 
 * @param {*} taskInfo 
 * @param {*} userInfo 
 * @param {*} callFun 
 */
function _sendNewsMsg(openid,accessToken,taskInfo,userInfo,isCps,callFun){
    const url = `https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=${accessToken}`;
    let content = _strReplace(taskInfo.content,userInfo,taskInfo.wechatInfo,isCps);
    let news = {};
    if(isCps){
        news = content;
    }else{
        let ranNum  = Math.ceil(Math.random()*content.articles.length) - 1;
        let _content = content.articles.splice(ranNum,1);
        news = {articles: _content};
    }
    if(news){
        const data = {
            touser: openid,
            msgtype: 'news',
            news: news
        }
        _sendPost(url,data,(err,res,body) => {
            callFun(err,body);
        });
    }else{
        callFun('图文内容为空');
    }
}

/**
 * 字符替换
 * @param {*} str 
 * @param {*} userInfo 
 * @param {*} wechatInfo 
 * @param {*} pure 
 */
function _strReplace(str,userInfo,wechatInfo,isCps,pure = null){
    const rStr = str.replace(/\{domain\}/g,isCps?wechatInfo.tg_domain:wechatInfo.domain)
        .replace(/\{username\}/g,userInfo.username)
        .replace(/\{wename\}/g,userInfo.username)
        .replace(/\{novel_domain}/g,wechatInfo.domain)
        .replace(/\{book_bean\}/g,userInfo.book_bean);
    
    if(pure){
        return rStr;
    }
    
    try{
        return JSON.parse(rStr);
    }catch(e){

    }
}

/**
 * 发送请求
 * @param {*} url 
 * @param {*} data 
 * @param {*} callFun 
 */
function _sendPost(url,data,callFun){
    request({
        url: url,
        method: "POST",
        json: true,
        headers: {"content-type": "application/json"},
        body: data
    }, (error, response, body) => {
        callFun && callFun(error,response,body);
    });
}

/**
 * 发送
 * @param {*} taskInfo 
 * @param {*} userInfo 
 */
function sendMsg(taskInfo,userInfo,isCps = 0){
    const accessToken = taskInfo.wechatInfo.accessToken;
    let openid = userInfo.openid;
    if(env.DEBUG === '1' && env.TESTOPENID){
        openid = env.TESTOPENID;
    }
    
    return new Promise((resolve,reject) => {
        if(taskInfo.msg_type === 1){
            _sendTmpMsg(openid,accessToken,taskInfo,userInfo,isCps,(err,res) => {
                if(err){
                    console.log(err);
                    reject(err);return;
                }
                res['msy_type_name'] = '模版消息';
                resolve(res);
            });
        }else{
            let _msgType = taskInfo.msg_type;
            if(isCps){
                if(taskInfo.msg_type === 2){
                    _msgType = 3
                }else{
                    _msgType = 2
                }
            }

            if(_msgType === 2){
                _sendTextMsg(openid,accessToken,taskInfo,userInfo,isCps,(err,res) => {
                    if(err){
                        reject(err);return;
                    }
                    res['msy_type_name'] = '文本消息';
                    resolve(res);
                });
            }else if(_msgType === 3){
                _sendNewsMsg(openid,accessToken,taskInfo,userInfo,isCps,(err,res) => {
                    if(err){
                        reject(err);return;
                    }
                    res['msy_type_name'] = '图文消息';
                    resolve(res);
                });
            }else{
                console.log('未知消息类型，请联系管理员处理');
                reject('未知消息类型，请联系管理员处理');
            }
        }
    });
}

module.exports = sendMsg;